package cn.edu.swu.io;

import java.util.Scanner;

public class Main {
    private ImageManager imageManager;
    private Scanner scanner;

    public Main() {
        imageManager = new ImageManager();
        scanner = new Scanner(System.in);
    }

    private void displayMenu() {
        System.out.println("\n=== 图片下载系统 ===");
        System.out.println("1. 下载图片");
        System.out.println("2. 查看所有图片");
        System.out.println("3. 搜索图片");
        System.out.println("4. 退出");
        System.out.print("请选择操作 (1-4): ");
    }

    private void handleDownload() {
        System.out.print("请输入图片URL: ");
        String url = scanner.nextLine().trim();

        if (url.isEmpty()) {
            System.out.println("URL不能为空！");
            return;
        }

        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            System.out.println("URL格式不正确，请以 http:// 或 https:// 开头");
            return;
        }

        imageManager.downloadImage(url);
    }

    private void handleSearch() {
        System.out.print("请输入要搜索的图片名称: ");
        String name = scanner.nextLine().trim();

        if (name.isEmpty()) {
            System.out.println("搜索关键词不能为空！");
            return;
        }

        imageManager.searchImage(name);
    }

    public void run() {
        System.out.println("欢迎使用图片下载系统！");
        System.out.println("图片将保存到: D:\\Java\\workspace\\2_java_io\\images\\");

        while (true) {
            displayMenu();
            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    handleDownload();
                    break;
                case "2":
                    imageManager.listImages();
                    break;
                case "3":
                    handleSearch();
                    break;
                case "4":
                    System.out.println("感谢使用图片下载系统，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入数字 1-4");
            }
        }
    }

    public static void main(String[] args) {
        Main app = new Main();
        app.run();
    }
}
